package com.bitbank.smartdevice.manager

/**
 *  Date：2018/12/19
 *  Author：xulee
 *  Desc：
 */
import android.app.Activity
import android.content.Context
import com.qmuiteam.qmuidemo.manager.QDPreferenceManager

/**
 * Created by cgspine on 2018/1/14.
 */

class QDUpgradeManager private constructor(context: Context) {
    private var mUpgradeTipTask: UpgradeTipTask? = null

    private val mContext: Context = context.applicationContext

    fun check() {
        val oldVersion = QDPreferenceManager.getInstance(mContext).versionCode
        val currentVersion = sCurrentVersion
        if (currentVersion > oldVersion) {
            if (oldVersion == INVALIDATE_VERSION_CODE) {
                onNewInstall(currentVersion)
            } else {
                onUpgrade(oldVersion, currentVersion)
            }
            QDPreferenceManager.getInstance(mContext).setAppVersionCode(currentVersion)
        }
    }

    private fun onUpgrade(oldVersion: Int, currentVersion: Int) {
        mUpgradeTipTask = UpgradeTipTask(oldVersion, currentVersion)
    }

    private fun onNewInstall(currentVersion: Int) {
        mUpgradeTipTask = UpgradeTipTask(INVALIDATE_VERSION_CODE, currentVersion)
    }

    fun runUpgradeTipTaskIfExist(activity: Activity) {
        mUpgradeTipTask?.upgrade(activity)
        mUpgradeTipTask = null
    }

    companion object {
        val INVALIDATE_VERSION_CODE = -1

        val VERSION_1_1_0 = 110
        val VERSION_1_1_1 = 111
        val VERSION_1_1_2 = 112
        val VERSION_1_1_3 = 113
        val VERSION_1_1_4 = 114
        val VERSION_1_1_5 = 115
        val VERSION_1_1_6 = 116
        val VERSION_1_1_7 = 117
        val VERSION_1_1_8 = 118
        val VERSION_1_1_9 = 119
        val VERSION_1_1_10 = 1110
        private val sCurrentVersion = VERSION_1_1_10
        private var sQDUpgradeManager: QDUpgradeManager? = null

        fun getInstance(context: Context): QDUpgradeManager {
            if (sQDUpgradeManager == null) {
                sQDUpgradeManager = QDUpgradeManager(context)
            }
            return sQDUpgradeManager as QDUpgradeManager
        }
    }
}